package de.devisnik.eidle.picture;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.net.MalformedURLException;
import java.net.URL;

import org.eclipse.jface.resource.ImageDescriptor;


public class FileUtils {
	private final static FilenameFilter IMAGE_FILENAME_FILTER = new FilenameFilter() {

		public boolean accept(File dir, String name) {
			String lowerCaseName = name.toLowerCase();
			return lowerCaseName.endsWith(".bmp")
					|| lowerCaseName.endsWith(".gif")
					|| lowerCaseName.endsWith(".jpg");
		}
	};

	public static ImageDescriptor[] getImagesInDirectory(final String directory) {
		final FileProvider fileProvider = new FileProvider(
				IMAGE_FILENAME_FILTER);
		try {
			fileProvider.addResource(new File(directory));
			final ImageDescriptor[] descriptors = new ImageDescriptor[fileProvider
					.getSize()];
			for (int i = 0; i < descriptors.length; i++) {
				final File file = fileProvider.getNext();
				descriptors[i] = createImageDescriptor(file);
			}
			return descriptors;
		} catch (final FileNotFoundException e) {
			e.printStackTrace();
			return new ImageDescriptor[] { ImageDescriptor
					.getMissingImageDescriptor() };
		}

	}

	private static ImageDescriptor createImageDescriptor(final File file) {

		try {
			final URL fileURL = file.toURL();
			return ImageDescriptor.createFromURL(fileURL);
		} catch (final MalformedURLException e) {
			e.printStackTrace();
			return ImageDescriptor.getMissingImageDescriptor();
		}
	}

}
